package com.ymy.thinking.in.spring.dependency.lookup;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * {@link NoUniqueBeanDefinitionException}
 * 按类型查找, Bean 的定义信息不唯一时
 *
 * @author Ringo
 * @date 2021/9/9 18:34
 */
public class NoUniqueBeanDefinitionExceptionDemo {
    public static void main(String[] args) {
        // 创建 IoC 容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(Config.class);

        // 开始 Spring 应用上下文
        applicationContext.refresh();

        try {
            String bean = applicationContext.getBean(String.class);
            System.out.println(bean);
        } catch (NoUniqueBeanDefinitionException e) {
            int nums = e.getNumberOfBeansFound();
            Class<?> beanType = e.getBeanType();
            System.err.printf("IoC 容器中存在 %d 个 【%s】 类型的 Bean, 具体原因：%s",
                    nums, beanType, e.getMessage());
        }

        // 关闭 Spring 应用上下文
        applicationContext.close();

    }

    public static class Config {
        @Bean
        public String hello() {
            return "hello";
        }

        @Bean
        public String world() {
            return "world";
        }
    }
}
